package com.liuzy.openapi;

import java.util.Random;

import com.liuzy.tool.HTTP;
import com.liuzy.tool.JSON;
import com.liuzy.util.MD5;

/**
 * http://api.fanyi.baidu.com/ http://dwz.cn/api
 * 
 * @author liuzy
 * @since 2015年10月18日
 */
public class BaiduApi {
	public static void main(String[] args) {
		System.out.println(shortUrl("http://www.sina.com/"));
		System.out.println(fanyi("你好"));
	}

	public static String appId = "20160223000013166";
	public static String key = "CKcbgihNkrjWxQajZPOz";

	public static String fanyi(String content) {
		HTTP http = new HTTP();
		http.put2url("q", content);
		http.put2url("from", "auto");
		http.put2url("to", "auto");
		http.put2url("appid", appId);
		String salt = "" + new Random().nextInt(2147483647);
		http.put2url("salt", salt);
		http.put2url("sign", MD5.md5(appId + content + salt + key));
		return http.doGET("http://api.fanyi.baidu.com/api/trans/vip/translate");
	}

	public static String shortUrl(String url) {
		HTTP http = new HTTP();
		http.put2body("url", url);
		String jsonStr = http.doPOST("http://dwz.cn/create.php");
		JSON json = null;
		try {
			json = new JSON(jsonStr);
			return json.get("tinyurl").value();
		} catch (Exception e) {
			return json.get("err_msg").value();
		}
	}
}
